<template>
  <li class="fx-select-option" v-bind="$attrs"
      :class="{active:activeClass,disabled}" @click.stop="optionClick">
    <slot>{{ label }}</slot>
  </li>
</template>

<script lang="ts">
import { defineComponent, PropType, inject, onMounted, Ref, computed } from 'vue'
import { ModelValueProps } from '../select/select.vue'
import { Emitter } from 'mitt'

interface SelectOptionProps {
  label: string | number,
  value: string | number,
  disabled: boolean
}

export default defineComponent({
  name: 'FOption',
  inheritAttrs: true,
  props: {
    label: {
      type: [String, Number] as PropType<string | number>,
      default: '',
      required: true
    },
    value: {
      type: [String, Number] as PropType<string | number>,
      default: '',
      required: true
    },
    // 禁用
    disabled: {
      type: Boolean as PropType<boolean>,
      default: false
    }
  },
  setup (props: SelectOptionProps) {
    // 当前选中
    const currentSelectValue = inject<Ref<ModelValueProps> | undefined>('selectValue', undefined)
    // 事件监听
    const selectMittEmit = inject<Emitter['emit']>('selectMittEmit')

    // 点击
    const optionClick = (): void => {
      if (props.disabled) return
      if (selectMittEmit) {
        selectMittEmit('selectMitt', {
          label: props.label,
          value: props.value
        })
      }
    }
    // 当前选中
    const activeClass = computed<boolean>(() => {
      const selectValue = currentSelectValue
      if (!selectValue) return false
      if (selectValue.value instanceof Array) {
        return selectValue.value.some((item: string | number) => item && item === props.value)
      } else {
        return selectValue.value === props.value
      }
    })

    onMounted(() => {
      if (selectMittEmit) {
        selectMittEmit('selectDataMitt', {
          label: props.label,
          value: props.value
        })
      }
    })

    return {
      currentSelectValue,
      activeClass,
      optionClick
    }
  }
})
</script>
